package com.jiepos.mpos.pay.quickpay.service.xk77pay;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Base64;

import com.jiepos.mpos.common.constant.SystemConstant;

/**
* 标题:
* 模块: 欣客支付帮助类
* 描 述: <描述>
* 版权: Copyright (c) 2017 江苏杰博实信息技术有限公司
* @author 杨剑武
* @version 1.0
* @since 2018年1月26日
* @history（历次修订内容、修订人、修订时间等）
*/

public class PayHelper {
	private static final char[] base64EncodeChars = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
			'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
			'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0',
			'1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };

	public static String getMD5Str(String sMsg) throws UnsupportedEncodingException {
		byte[] msg = sMsg.getBytes(SystemConstant.UTF_ENCODING);
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(msg);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		byte[] b = messageDigest.digest();
		return new String(Base64.encodeBase64(b));
	}

	public static String getEncodeStr(String str) {
		byte[] bytes = (byte[]) null;
		try {
			bytes = str.getBytes(SystemConstant.UTF_ENCODING);
		} catch (Exception e) {
			e.printStackTrace();
		}
		StringBuilder sb = new StringBuilder(bytes.length * 2);

		for (int i = 0; i < bytes.length; i++) {
			sb.append("0123456789ABCDEF".charAt((bytes[i] & 0xF0) >> 4));
			sb.append("0123456789ABCDEF".charAt((bytes[i] & 0xF) >> 0));
		}
		return sb.toString();
	}

	/**
	 * 将字节数组编码为字符串
	 * 
	 * @param data
	 */
	public static String encode(byte[] data) {
		StringBuffer sb = new StringBuffer();
		int len = data.length;
		int i = 0;
		int b1, b2, b3;

		while (i < len) {
			b1 = data[i++] & 0xff;
			if (i == len) {
				sb.append(base64EncodeChars[b1 >>> 2]);
				sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
				sb.append("==");
				break;
			}
			b2 = data[i++] & 0xff;
			if (i == len) {
				sb.append(base64EncodeChars[b1 >>> 2]);
				sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
				sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
				sb.append("=");
				break;
			}
			b3 = data[i++] & 0xff;
			sb.append(base64EncodeChars[b1 >>> 2]);
			sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
			sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
			sb.append(base64EncodeChars[b3 & 0x3f]);
		}
		return sb.toString();
	}

	public static String filter(String str) throws UnsupportedEncodingException {
		String output = null;
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < str.length(); i++) {
			int asc = str.charAt(i);
			if ((asc != 10) && (asc != 13))
				sb.append(str.subSequence(i, i + 1));
		}
		output = new String(sb.toString().getBytes(), SystemConstant.UTF_ENCODING);
		return output;
	}
	
	public static String build(String[] keys, String[] params,
            String service, String key) throws UnsupportedEncodingException {
		String str = _MakeURL(keys, params);
		String sign = getMD5Str(str + key);
		//System.out.println(str);
		
		String resp = "";
		StringBuilder sb = new StringBuilder(str.toString());
		sb.append("&");
		sb.append("sign");
		sb.append('=');
		sb.append(sign);
		//System.out.println(sb.toString());
		
		String paramStr = getEncodeStr(sb.toString());
		String finalStr = encode(paramStr.getBytes());
		try {
		finalStr = filter(finalStr);
		finalStr = URLEncoder.encode(finalStr, "UTF-8");
		} catch (UnsupportedEncodingException e1) {
		e1.printStackTrace();
		}
		
		String param = "sText=" + finalStr;
		//System.out.println(param);
		
		InputStream is = null;
		HttpURLConnection httpUrlConnection = null;
		try {
		URL url = new URL(service);
		URLConnection urlConnection = url.openConnection();
		httpUrlConnection = (HttpURLConnection) urlConnection;
		
		httpUrlConnection.setDoOutput(true);
		httpUrlConnection.setDoInput(true);
		httpUrlConnection.setUseCaches(false);
		httpUrlConnection.setRequestMethod("POST");
		
		httpUrlConnection.setRequestProperty("Content-Type",
		 "application/x-www-form-urlencoded");
		httpUrlConnection.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
		httpUrlConnection.setRequestProperty("Charset", "UTF-8");
		
		httpUrlConnection.connect();
		
		DataOutputStream dos = new DataOutputStream(httpUrlConnection.getOutputStream());
		dos.writeBytes(param);
		dos.flush();
		dos.close();
		
		int resultCode = httpUrlConnection.getResponseCode();
		if (HttpURLConnection.HTTP_OK == resultCode) {
		StringBuffer sb1 = new StringBuffer();
		String readLine = new String();
		BufferedReader responseReader = new BufferedReader(
		     new InputStreamReader(httpUrlConnection.getInputStream(), "UTF-8"));
		while ((readLine = responseReader.readLine()) != null) {
		 sb1.append(readLine).append("\n");
		}
		responseReader.close();
		//System.out.println(sb1.toString());
		resp = sb1.toString();
		}
		} catch (Exception e) {
		e.printStackTrace();
		} finally {
		if (is != null) {
		try {
		 is.close();
		} catch (IOException e) {
		 e.printStackTrace();
		}
		}
		if (httpUrlConnection != null) {
		httpUrlConnection.disconnect();
		}
		}
		
		return resp;
	}
	
	public static String _MakeURL(String[] keys, String[] params) {
        if (keys.length != params.length) {
            return null;
        }

        StringBuilder url = new StringBuilder();
        for (int i = 0; i < params.length; i++) {
            url.append('&');
            url.append(keys[i]);
            url.append('=');
            url.append(params[i]);
        }

        return url.toString().replaceFirst("&", "");
    }
}
